<?php

namespace app\data\controller\record;

use app\admin\service\FeiShuService;
use app\admin\service\WxWorkService;
use app\data\service\CityUserRelationService;
use app\data\service\RecordService;
use app\data\service\ReworkService;
use app\data\service\StringParse;
use think\admin\Controller;
use think\admin\service\AdminService;
use think\facade\Cache;

/**
 * 运满满运营信息采集
 * Class CarRecordOperate
 * @package app\data\controller\user
 */
class CarRecordOperate extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'data_record';

    /**
     * 运满满运营信息采集
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $ts['ta'] = ['vip' => '', 'name' => '全部记录', 'count' => 0];
        $this->total = $ts;

        // 设置页面标题time_docking
        if ($this->request->request('menu_type') == 'operate') {
            $this->title = '运满满运营信息采集';
            // 创建查询对象
            $query = $this->_query($this->table)->order('id desc');
        } else {
            $this->title = '对接人信息采集';

            // 创建查询对象
            $query = $this->_query($this->table)->order('id desc');

            if (!AdminService::instance()->isSuper()) {
                $query->where('uuid_docking', AdminService::instance()->getUserId());
            } else {
                $uuidCityName = $this->request->request('uuid_city_name', '');
                if (!empty($uuidCityName)) {
                    $uuidCityIds = $this->app->db->name('work_user')->where('name', 'like', "%{$uuidCityName}%")->column('id');
                    $query->whereIn('uuid_city', $uuidCityIds);
                }
            }
        }

        $this->menu_type = $this->request->request('menu_type');

        $query->like('phone,username,plate_number')->equal('id,province#query_province,city#query_city,area#query_area,paint_status,end_paint_status,fail_status,is_deal,is_rework')->dateBetween('time_docking,time_complete');


        // 列表选项卡
        $this->type = trim(input('type', 'ta'), 't');
        if ($this->type === '1') {
            $query->whereIn('paint_status', [-1, 0])->whereNull('time_invite')->where('invite_remark', '');
        } else if ($this->type === '2') {
            $query->whereIn('paint_status', [-1, 0]);
        }

        $uuidCityName = $this->request->request('uuid_city_name', '');
        if (!empty($uuidCityName)) {
            $uuidCityIds = $this->app->db->name('work_user')->where('name', 'like', "%{$uuidCityName}%")->column('id');
            $query->whereIn('uuid_city', $uuidCityIds);
        }

        $uuidDockingName = $this->request->request('uuid_docking_name', '');
        if (!empty($uuidDockingName)) {
            $uuidDockingIds = $this->app->db->name('work_user')->where('name', 'like', "%{$uuidDockingName}%")->column('id');
            $query->whereIn('uuid_docking', $uuidDockingIds);
        }

        // 数据查询分页
        if (input('output') == 'json') {
            $query = $query->page(true, false);
            $this->success('', $query);
        } else {
            $query->page();
        }
    }

    /**
     * 运满满运营信息采集导出
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function indexExport()
    {
        $this->index();
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _indexExport_page_filter(array &$data)
    {
        $this->_page_filter($data);
    }

    /**
     * 搜索
     * @return void
     */
    public function search()
    {
        $keyword = $this->request->request('keyword');
        if (empty($keyword)) {
            $this->success('', []);
        }
        $adminId = AdminService::instance()->getUserId();
        $response = $this->app->db->name($this->table)
            ->field('id,username,plate_number')
            ->where('uuid_city', $adminId)
            ->where(function ($where) use ($keyword) {
                return $where->where('username', 'like', "%{$keyword}%")->whereOr('plate_number', 'like', "%{$keyword}%");
            })->select()->toArray();

        foreach ($response as &$item) {
            $item['url'] = config('fei_shu.url') . "/data/record.car_record_complete/edit.html?show=car_record_complete&id={$item['id']}";
        }
        $this->success('', $response);
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _page_filter(array &$data)
    {
        RecordService::instance()->format($data);

        $ids = array_column($data, 'id');
        $recordRemarkLogs = $this->app->db->name('data_record_remark_log')->whereIn('record_id', $ids)->order('id', 'desc')->select()->toArray();
        foreach ($recordRemarkLogs as $recordRemarkLog) {
            if (empty($id2reason[$recordRemarkLog['record_id']])) {
                $id2reason[$recordRemarkLog['record_id']] = $recordRemarkLog['remark'];

                if (!empty($recordRemarkLog['remind_at']) && date('Y-m-d', strtotime($recordRemarkLog['remind_at'])) == date('Y-m-d')) {
                    $showRed[$recordRemarkLog['record_id']] = 1;
                }
            }
        }

        foreach ($data as &$item) {
            if (is_string($item['time_invites'])) {
                $item['time_invites'] = explode("\n", $item['time_invites']);
                foreach ($item['time_invites'] as $key => $time) {
                    if (empty($time)) {
                        unset($item['time_invites'][$key]);
                    }
                }
            } else {
                $item['time_invites'] = [];
            }

            $item['analyze_reason_text'] = RecordService::instance()->analyzeReasons($item['analyze_reason']) ?: '暂无';
            $item['remark'] = $id2reason[$item['id']] ?? '暂无';
            $item['remark_show_red'] = $showRed[$item['id']] ?? 0;
        }
    }

    /**
     * 表单结果处理
     * @param boolean $state
     */
    protected function _form_result(bool $state, array $data)
    {
        if ($state) {
            if ($this->isMobile()) {
                $this->success('保存成功！');
            } else {
                $this->success('保存成功！');
            }
        }
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _teams_page_filter(array &$data)
    {
    }

    /**
     * 编辑
     * http://youkejia.test/data/record.car_record_operate/edit.html?show_id=1000&id=1000
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if ($this->isMobile()) {
            $template = 'form_mobile';
        } else {
            $template = 'form';
            if (!empty($showId = request()->get('show_id', 0))) {
                return redirect(getHttpHost() . "/admin.html#/data/record.car_record_operate/index.html?show_id={$showId}");
            }
        }

        $this->_form($this->table, $template);
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        $this->title = '信息采集管理';
        if ($this->request->isPost()) {
            // 检查登录账号是否出现重复

            $record = $this->app->db->name('data_record')->where('id', $data['id'])->findOrEmpty();

            if (!$record['is_rework'] && $data['is_rework'] && $data['uuid_city'] == sysdata('DefaultCityUuid')) {
                $this->error('请转单到正确施工负责人，在进行标记返工');
            }

            if (!empty($data['phone'])) {
                $where = ['phone' => $data['phone']];
//                if ($this->app->db->name($this->table)->whereNotIn('id', [$data['id']])->where($where)->count() > 0) {
//                    $this->error("手机号已经存在，请使用其它手机号！");
//                }

                [$digits, $chinese] = StringParse::instance()->splitDigitsAndChinese($data['car_vehicle_type']);
                $carVehicleTypeId = StringParse::instance()->carVehicleType($digits, $chinese);
                if (!empty($carVehicleTypeId)) {
                    $data['car_vehicle_type_id'] = $carVehicleTypeId;
                }

                if ($data['paint_status'] == 1) {
                    if (empty($data['painter'])) {
                        $this->error('喷漆师傅不能为空');
                    }

                    if (in_array($record['paint_status'], [-1, 0])) {
                        $data['time_complete'] = date('Y-m-d H:i:s');
                    } else {
                        $data['time_complete'] = null;
                    }
                    $data = CityUserRelationService::instance()->calcPaintPrice($record, $data);
                }
            }
            if (empty($data['time_invite'])) {
                unset($data['time_invite']);
            }
            if (empty($data['time_plan'])) {
                unset($data['time_plan']);
            }
            if (empty($data['time_docking'])) {
                unset($data['time_docking']);
            }
            if (empty($data['time_complete'])) {
                unset($data['time_complete']);
            }
            if (!empty($data['invite_remark']) && empty($data['time_invite']) && empty($record['time_invite'])) {
                $data['time_invite'] = date('Y-m-d H:i:s');
            }
            if (!empty($record['time_invite'])) {
                unset($data['time_invite']);
            }

            // 生成品质解锁记录
            if (!empty($data['is_rework'])) {
                ReworkService::instance()->saveReworkRecord($record, $data);

                //如果返工的话需要把已完成改为未完成
                $data['paint_status'] = 0;
            }
        } else {
            $this->users = $this->app->db->name('work_user')->where('authorize', 'like', "%2%")->order('id desc')->select()->toArray();
            $this->cityUsers = $this->app->db->name('work_user')->where('authorize', 'like', "%3%")->order('id desc')->select()->toArray();
            $data = RecordService::instance()->formatOne($data);
            $data = ReworkService::instance()->formatRework($data);
        }
    }

    /**
     * 删除
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->app->db->name($this->table)->where('id', input('id'))->delete();
        $cacheKey = config('cacheKey.uid2user') . input('id');
        Cache::delete($cacheKey);
        $this->success('删除成功');
    }

    /**
     * 转单
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function turnOrder()
    {
        $data = $this->_vali([
            'id.require' => 'id不能为空！',
            'data.require' => 'data不能为空！'
        ]);
        $uuid = explode('#', $data['data'])[0];

        $openId = $this->app->db->name('work_user')->where('id', $uuid)->value('open_id');
        if (empty($openId)) {
            $this->error('该员工异常，无法转发给该员工');
        }

        $record = $this->app->db->name($this->table)->where('id', $data['id'])->findOrEmpty();
        if (!$record) {
            $this->error('查无该记录信息');
        }

        if ($record['uuid_city'] == $uuid) {
            $this->error('该单子已经属于该员工了');
        }

        // 发送企业微信消息
        $message = RecordService::instance()->toForwardText($record, 'docking');
        FeiShuService::instance()->sendMessageTextByUserid($openId, $message);

        if (!empty($uuid)) {
            $result = $this->app->db->name($this->table)->where('id', $data['id'])->update(['uuid_city' => $uuid]);
            if (!$result) {
                $this->error('转发给员工失败');
            }
        }

        $this->success('转发给员工成功');
    }

    /**
     * 再次跟单
     * @auth
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function againOrder()
    {
        if ($this->request->isGet()) {
            $data = $this->_vali([
                'id.require' => 'id不能为空！',
            ]);

            $this->uuid_city = $this->app->db->name($this->table)->where('id', $data['id'])->value('uuid_city');
            $this->id = $data['id'];

            $this->users = $this->app->db->name('work_user')->where('authorize', 'like', "%3%")->order('id desc')->select()->toArray();

            $this->fetch();
        } else {
            $data = $this->_vali([
                'id.require' => 'id不能为空！',
                'uuid.require' => 'data不能为空！'
            ]);

            $uuid = $data['uuid'];

            $openId = $this->app->db->name('work_user')->where('id', $uuid)->value('open_id');
            if (empty($openId)) {
                $this->error('该员工异常，无法转发给该员工');
            }

            $record = $this->app->db->name($this->table)->where('id', $data['id'])->findOrEmpty();
            if (!$record) {
                $this->error('查无该记录信息');
            }

            $this->app->db->name($this->table)->where('id', $data['id'])->update(['uuid_city' => $uuid]);

            $this->app->db->name('data_record_again_log')->insert([
                'record_id' => $data['id'],
                'uuid_city' => $uuid,
                'create_at' => date('Y-m-d H:i:s'),
            ]);

            // 发送企业微信消息
            $message = RecordService::instance()->toForwardText($record, 'docking');
            FeiShuService::instance()->sendMessageTextByUserid($openId, $message);

            $this->success('再次跟单成功');
        }
    }
}